
import { Injectable } from "@nestjs/common";
import { ResultData } from "@/common/utils/result";
import { InjectRepository } from "@nestjs/typeorm";
import { Repository } from "typeorm";
import { Role } from "@/modules/system/role/entities/role.entity";
import { User } from "@/modules/system/user/entities/user.entity";

@Injectable()
export class RoleService {
	constructor(
		@InjectRepository(Role)
		private readonly roleRepository: Repository<Role>,
		@InjectRepository(User)
		private readonly userRepository: Repository<User>
	) {
	}
	
	//给用户添加角色
	async userAssignRole({ roleIds, userId }) {
		// 新增 向中间表中插入数据
		return ResultData.ok(
			await this.userRepository.createQueryBuilder()
				.insert()
				.into("users_roles")
				.values(roleIds.map(v => ({ userId: userId, rolesId: v })))
				.execute()
		);
		
		// 删除
		return ResultData.ok(
			await this.userRepository.createQueryBuilder("user_role")
				.delete()
				.from("user_role")
				.where("user_role.userId = :userId", { userId: 1 })
				.execute()
		);
		
		// 更新
		return ResultData.ok(
			await this.userRepository.createQueryBuilder()
				.createQueryBuilder()
				.update("user_role")
				.set({
					roleId: 2
				})
				.where("user_role.userId = :userId", { userId: 1 })
				.execute()
		);
		
		//查询
		return ResultData.ok(
			await this.userRepository.createQueryBuilder()
				.createQueryBuilder()
				.select()
				.from("user_role", "user_role")
				.where("user_role.roleId = :roleId", { roleId: 2 })
				.getRawMany()
		);
		
	}
	
	
}
